package com.gobang.controller;

import com.gobang.domain.dto.UserRegisterDTO;
import com.gobang.domain.vo.Result;
import com.gobang.domain.vo.UserInfoVO;
import com.gobang.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;

/**
 * 用户管理控制器
 * 处理用户注册、查询等相关请求
 * 
 * @author System
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@Validated
public class UserController {

    private final UserService userService;

    /**
     * 用户注册
     *
     * @param registerDTO 注册请求数据
     * @param request HTTP请求对象
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<UserInfoVO> register(@Valid @RequestBody UserRegisterDTO registerDTO, 
                                      HttpServletRequest request) {
        log.info("用户注册请求，用户名：{}", registerDTO.getUsername());
        
        try {
            UserInfoVO userInfo = userService.register(registerDTO);
            log.info("用户注册成功，用户ID：{}，用户名：{}", userInfo.getId(), userInfo.getUsername());
            return Result.success(userInfo, "注册成功").withPath(request.getRequestURI());
        } catch (Exception e) {
            log.error("用户注册失败，用户名：{}，错误：{}", registerDTO.getUsername(), e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 根据用户ID查询用户信息
     *
     * @param userId 用户ID
     * @param request HTTP请求对象
     * @return 用户信息
     */
    @GetMapping("/{userId}")
    public Result<UserInfoVO> getUserInfo(@PathVariable Long userId, 
                                         HttpServletRequest request) {
        log.info("查询用户信息，用户ID：{}", userId);
        
        try {
            UserInfoVO userInfo = userService.getUserById(userId);
            log.info("用户信息查询成功，用户ID：{}，用户名：{}", userId, userInfo.getUsername());
            return Result.success(userInfo, "查询成功").withPath(request.getRequestURI());
        } catch (Exception e) {
            log.error("用户信息查询失败，用户ID：{}，错误：{}", userId, e.getMessage(), e);
            throw e;
        }
    }
} 